#include "server.h"
#include "ui_server.h"
#include <QMessageBox>
#include <QDateTime>
#include <QSqlError>
#include <QJsonDocument>
#include <QJsonObject>

Server::Server(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Server)
{
    ui->setupUi(this);

    // 初始化数据库
    initDatabase();


    // 创建TCP服务器
    tcpServer = new QTcpServer(this);

    // 连接信号
    connect(tcpServer, &QTcpServer::newConnection, this, &Server::newConnection);

    // 设置窗口标题
    this->setWindowTitle("车辆进出记录服务器");

    // 初始化记录列表
    updateRecordList();
}

Server::~Server()
{
    // 关闭所有客户端连接
    for (QTcpSocket *client : clients) {
        client->close();
        client->deleteLater();
    }

    // 关闭数据库
    if (db.isOpen()) {
        db.close();
    }

    delete ui;
}

void Server::initDatabase()
{
    // 初始化SQLite数据库
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("car_records.db");

    if (!db.open()) {
        QMessageBox::critical(this, "数据库错误", "无法打开数据库: " + db.lastError().text());
        return;
    }

    // 创建表（如果不存在）
    QSqlQuery query;
    if (!query.exec("CREATE TABLE IF NOT EXISTS car_records ("
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                    "plate_number TEXT NOT NULL, "
                    "brand TEXT, "
                    "series TEXT, "
                    "type TEXT, "
                    "color TEXT, "
                    "enter_time TEXT NOT NULL, "
                    "leave_time TEXT)")) {
        qDebug() << "创建表失败:" << query.lastError().text();
    }

    // 添加索引提高查询效率
    query.exec("CREATE INDEX IF NOT EXISTS idx_plate ON car_records (plate_number)");
    query.exec("CREATE INDEX IF NOT EXISTS idx_enter_time ON car_records (enter_time)");
}

void Server::saveToDatabase(const QString &plate, const QString &brand,
                            const QString &series, const QString &type,
                            const QString &color, const QString &enterTime,
                            const QString &leaveTime)
{
    QSqlQuery query;
    query.prepare("INSERT INTO car_records (plate_number, brand, series, type, color, enter_time, leave_time) "
                  "VALUES (:plate, :brand, :series, :type, :color, :enterTime, :leaveTime)");

    query.bindValue(":plate", plate);
    query.bindValue(":brand", brand);
    query.bindValue(":series", series);
    query.bindValue(":type", type);
    query.bindValue(":color", color);
    query.bindValue(":enterTime", enterTime);
    query.bindValue(":leaveTime", leaveTime);

    if (!query.exec()) {
        QMessageBox::warning(this, "数据库错误", "保存记录失败: " + query.lastError().text());
    }
}

void Server::updateRecordList()
{
    ui->listWidget->clear();
    itemIdMap.clear(); // 清空映射

    QSqlQuery query("SELECT * FROM car_records ORDER BY enter_time DESC");
    while (query.next()) {
        int id = query.value("id").toInt();
        QString plate = query.value("plate_number").toString();
        QString brand = query.value("brand").toString();
        QString enterTime = query.value("enter_time").toString();
        QString leaveTime = query.value("leave_time").toString();

        // 格式化显示文本
        QString status = (leaveTime.isEmpty()) ? "在场" : "已离开";
        QString itemText = QString("%1 [%2] - 进入: %3").arg(plate).arg(status).arg(enterTime);

        if (status == "已离开") {
            itemText += QString(" - 离开: %1").arg(leaveTime);
        }

        QListWidgetItem *item = new QListWidgetItem(itemText);

        // 根据状态设置颜色
        item->setBackground(status == "在场" ? QColor(220, 255, 220) : QColor(240, 240, 240));

        ui->listWidget->addItem(item);
        itemIdMap[item] = id; // 存储记录ID与列表项的映射
    }
}

void Server::on_pushButton_clicked()
{
    if (tcpServer->isListening()) {
        tcpServer->close();
        ui->pushButton->setText("开始监听");
        ui->statusbar->showMessage("已停止监听");
    } else {
        if (tcpServer->listen(QHostAddress::Any, 8888)) {
            ui->pushButton->setText("停止监听");
            ui->statusbar->showMessage(QString("正在监听端口: %1").arg(tcpServer->serverPort()));
        } else {
            QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer->errorString());
        }
    }
}

void Server::newConnection()
{
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    clients.append(clientSocket);

    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::readyRead);
    connect(clientSocket, &QTcpSocket::disconnected, this, &Server::clientDisconnected);

    ui->statusbar->showMessage(QString("新客户端连接: %1:%2")
                                   .arg(clientSocket->peerAddress().toString())
                                   .arg(clientSocket->peerPort()));
}

void Server::readyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket) return;

    while (clientSocket->bytesAvailable()) {
        QByteArray data = clientSocket->readAll();
        qDebug() << "收到客户端数据:" << data;

        // 解析JSON数据
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);

        if (parseError.error != QJsonParseError::NoError) {
            qDebug() << "JSON解析错误:" << parseError.errorString();
            return;
        }

        if (!doc.isObject()) {
            qDebug() << "接收的数据不是JSON对象";
            return;
        }

        QJsonObject obj = doc.object();
        QString type = obj["type"].toString();

        if (type == "enter") {
            QString plate = obj["plate"].toString();
            QString brand = obj["brand"].toString();
            QString series = obj["series"].toString();
            QString carType = obj["car_type"].toString();
            QString color = obj["color"].toString();
            QString enterTime = obj["enter_time"].toString();

            // 保存到数据库
            saveToDatabase(plate, brand, series, carType, color, enterTime, "");

            // 更新UI
            updateRecordList();

        } else if (type == "exit") {
            QString plate = obj["plate"].toString();
            QString leaveTime = obj["leave_time"].toString();

            // 更新数据库记录 - 修复版
            QSqlQuery query;
            query.prepare("UPDATE car_records SET leave_time = :leaveTime "
                          "WHERE plate_number = :plate AND (leave_time IS NULL OR leave_time = '')");
            query.bindValue(":leaveTime", leaveTime);
            query.bindValue(":plate", plate);

            if (!query.exec()) {
                qDebug() << "更新离开时间失败:" << query.lastError().text();
            } else {
                // 检查更新是否成功
                if (query.numRowsAffected() == 0) {
                    qDebug() << "警告: 未找到匹配的记录更新离开时间";
                } else {
                    qDebug() << "成功更新离开时间，影响行数:" << query.numRowsAffected();
                }
            }

            // 更新UI
            updateRecordList();
        }
    }
}

void Server::clientDisconnected()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket) return;

    clients.removeOne(clientSocket);
    clientSocket->deleteLater();

    ui->statusbar->showMessage(QString("客户端断开连接，剩余连接: %1").arg(clients.size()));
}

void Server::on_Btn_Del_clicked()
{
    QList<QListWidgetItem*> selectedItems = ui->listWidget->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::information(this, "提示", "请选择要删除的记录。");
        return;
    }

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除", "确定要删除选中的记录吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        for (QListWidgetItem *item : selectedItems) {
            if (itemIdMap.contains(item)) {
                int recordId = itemIdMap[item];
                QSqlQuery query;
                query.prepare("DELETE FROM car_records WHERE id = :id");
                query.bindValue(":id", recordId);

                if (!query.exec()) {
                    QMessageBox::warning(this, "数据库错误", "删除记录失败: " + query.lastError().text());
                }
            }
        }
        updateRecordList(); // 更新列表
    }
}


void Server::on_Btn_Del_All_clicked()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除", "确定要删除所有记录吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        QSqlQuery query("DELETE FROM car_records");
        if (!query.exec()) {
            QMessageBox::warning(this, "数据库错误", "删除所有记录失败: " + query.lastError().text());
        } else {
            updateRecordList();
        }
    }
}

